'use strict';

const Service = require('egg').Service;
const crypto = require('crypto');

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserService extends Service {
  async login(userInfo) {
    const { ctx, app } = this;
    const pwd = this.getMd5Data(userInfo.password);
    const result = await app.model.query(`select * from user where tel = '${userInfo.contact}'
                    union select * from user where nickname = '${userInfo.contact}'
                    union select * from user where  email = '${userInfo.contact}'`,
    {
      type: app.Sequelize.QueryTypes.SELECT,
    });
    if (result) {
      if (result[0].password.toString() === pwd) {
        ctx.model.User.update(
          {
            updatedDate: Date.now(),
          },
          {
            where: {
              id: result[0].id,
            },
          }
        );
        const tokenID = ctx.getToken({
          id: result[0].id,
          contact: userInfo.contact,
        }, {
          expiresIn: '3day',
        });
        this.app.redis.setex(result[0].id, 60 * 30, tokenID);
        this.app.redis.setex(result[0].id + 'u', 60 * 30, JSON.stringify(result[0]));
        return {
          state: 200,
          msg: '登录成功',
          tokenID,
        };
      }
      return {
        state: 400,
        msg: '登录失败，帐号或密码错误',
      };
    }
    return {
      state: 400,
      msg: '此帐号末注册，请注册后重试',
    };
  }
  async getUser(id) {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
    if (id) {
      // return await ctx.model.User.findByPk(toInt(id));
      return await JSON.parse(await this.app.redis.get(id + 'u'));
    }
    return await ctx.model.User.findAll(query, {
      attrbutes: [ 'nickname' ],
      include: [{
        model: ctx.model.User,
        as: 'user',
        attributes: [ 'nickname' ],
      }],
    });
  }
  // 专门对数据进行md5加密的方法，输入明文返回密文
  getMd5Data(data) {
    return crypto.createHash('sha1').update(crypto.createHash('md5').update(crypto.createHash('sha1').update(data).digest('hex')).digest('hex')).digest('hex');
  }
}

module.exports = UserService;
